package utils

import (
	"encoding/base64"
	"fmt"
	"html/template"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strings"

	"go.mongodb.org/mongo-driver/bson/primitive"
)

func ProcessTemplates(path string) *template.Template {
	funcMap := template.FuncMap{
		"idToString": func(id *primitive.ObjectID) string {
			b, _ := id.MarshalJSON()
			return strings.ReplaceAll(string(b), "\"", "")
		},
		"sliceToString": func(val []string) string {
			return strings.Join(val, "")
		},
		"defaultToVal": func(val string) string {
			if len(strings.TrimSpace(val)) > 0 {
				return val
			}
			return "Anon"
		},
		"dateTimeToString": func(val primitive.DateTime) string {
			return val.Time().Format("2006/01/02 (Mon) 15:04:05")
		},
	}

	templates := template.Must(template.New("").Funcs(funcMap).ParseGlob(path))

	return templates
}

func SetSiteEnvs() (string, string) {
	siteName, nameOk := os.LookupEnv("SITE_NAME")
	siteTitle, titleOk := os.LookupEnv("SITE_TITLE")
	if !nameOk || siteName == "" {
		siteName = "Welcome to IMABON!"
	}
	if !titleOk || siteTitle == "" {
		siteTitle = "IMABON"
	}
	return siteName, siteTitle
}

func ProcessImage(req *http.Request) string {
	req.ParseMultipartForm(32 << 20)
	file, _, err := req.FormFile("image")

	var imgBase64Str string

	if file != nil {
		defer file.Close()
		if err != nil {
			fmt.Println(err)
		}

		fileData, err := ioutil.ReadAll(file)
		if err != nil {
			fmt.Println(err)
		}

		contentType := http.DetectContentType(fileData)

		if contentType != "image/png" &&
			contentType != "image/jpeg" &&
			contentType != "image/gif" &&
			contentType != "image/webp" {
			log.Printf("Type not supported yet: %s\n", contentType)
			return ""
		}

		imgBase64Str = base64.StdEncoding.EncodeToString(fileData)
		return imgBase64Str
	}
	return ""
}
